<template>
  <div class="app-container period-box">
    <div class="purchas-war">
      <el-row :gutter="30">
        <el-col :span="4">
          <div class="date-selection">
            <div class="date-top">
              <button
                type="button"
                aria-label="前一年"
                class="
                  el-picker-panel__icon-btn
                  el-date-picker__prev-btn
                  el-icon-d-arrow-left
                "
                @click="changeYear('last')"
              ></button>
              <span style="font-size: 15px"
                >{{ queryMonth.year }}<label>年结存期间</label></span
              >
              <button
                type="button"
                aria-label="后一年"
                class="
                  el-picker-panel__icon-btn
                  el-date-picker__next-btn
                  el-icon-d-arrow-right
                "
                @click="changeYear('next')"
              ></button>
            </div>
            <div class="date-content">
              <div class="content-mounth">
                <div v-for="(item, index) in MonthData" :key="index">
                  <span
                    :class="{
                      today: balanceMonthStatus['month' + (index + 1)],
                    }"
                    >{{ item }}</span
                  >
                </div>
              </div>
            </div>
          </div>
        </el-col>
        <el-col :span="20">
          <div class="con-top mb8">
            <div class="top-left">
              <el-row :gutter="10">
                <el-col :span="1.5">
                  <el-select
                    class="ware-sel"
                    v-model="selectwarehouse"
                    placeholder="请选择仓库"
                    @change="warehouseChange"
                  >
                    <el-option
                      v-for="item in optionswarehouse"
                      :key="item.uniqueId"
                      :label="item.name"
                      :value="item.code"
                    >
                    </el-option>
                  </el-select>
                </el-col>
                <el-col :span="1.5">
                  <el-button
                    type="primary"
                    v-hasPermi="['wm:period:query']"
                    plain
                    icon="el-icon-menu"
                    size="mini"
                    @click="checkAll"
                  >
                    查询所有
                  </el-button>
                </el-col>
                <el-col :span="1.5">
                  <el-button
                    type="primary"
                    v-hasPermi="['wm:period:permit']"
                    plain
                    icon="el-icon-s-management"
                    size="mini"
                    :disabled="
                      selectwarehouse == '' ||
                      periodDate == null ||
                      periodDate == ''
                    "
                    @click="handleBalance"
                    >结存
                  </el-button>
                </el-col>
                <el-col :span="1.5">
                  <el-button
                    type="info"
                    v-hasPermi="['wm:period:revoke']"
                    plain
                    icon="el-icon-s-management"
                    size="mini"
                    @click="handleCounterBalance"
                    >反结存
                  </el-button>
                </el-col>
                <el-col :span="1.5">
                  <el-button
                    type="warning"
                    plain
                    icon="el-icon-download"
                    size="mini"
                    @click="handleExport"
                    v-hasPermi="['wm:period:export']"
                    :disabled="
                      selectwarehouse == '' ||
                      periodDate == null ||
                      periodDate == ''
                    "
                    >导出</el-button
                  >
                </el-col>
                <el-col :span="1.5">
                  <el-button
                    type="success"
                    plain
                    icon="el-icon-printer"
                    size="mini"
                    @click="handlePrint"
                    v-hasPermi="['wm:period:print']"
                    :disabled="
                      selectwarehouse == '' ||
                      periodDate == null ||
                      periodDate == ''
                    "
                    >打印</el-button
                  >
                </el-col>
              </el-row>
            </div>
          </div>

          <!-- 结存仓库数据 -->
          <div class="ware-content">
            <div class="content-table">
              <el-table
                :data="BalanceData"
                border
                style="width: 100%"
                v-loading="loading"
                :height="maxHeight"
              >
                <el-table-column
                  type="index"
                  width="60"
                  align="center"
                  label="序号"
                >
                </el-table-column>
                <el-table-column label="仓库" align="center" prop="whName">
                </el-table-column>
                <el-table-column label="期间" align="center" prop="period">
                </el-table-column>
                <el-table-column prop="checkFlag" label="状态" align="center">
                  <template v-slot="scope">
                    <el-tag type="info" v-if="scope.row.checkFlag == '0'">
                      {{ scope.row.checkFlag | fliterFlag }}</el-tag
                    >

                    <el-tag v-if="scope.row.checkFlag == '1'">
                      {{ scope.row.checkFlag | fliterFlag }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column
                  prop="createTime"
                  label="操作日期"
                  align="center"
                >
                </el-table-column>
                <el-table-column prop="createBy" label="操作人" align="center">
                </el-table-column>
              </el-table>
            </div>
          </div>
        </el-col>
      </el-row>
    </div>
    <!-- 分页 -->
    <pagination
      v-if="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getBalanceList"
    />
    <!-- 打印数据 -->
    <PrintPage :printData="printData" :title="title" ref="startPrint" />
  </div>
</template>

<script>
import {
  listWarehouses, //仓库查询
  listBalance, //结存查询
  balanceWm, //结存
  aniBalanceWm, //反结存
  exportBalance, //导出
  blanceMonth, //结存日历
  blanceAvailable, //可结存期间
  blanceAll, //仓库所有结存期间
} from "../../api/period";
import PrintPage from "../../components/Period/print"; //分类组件
import print from "print-js"; //打印js
export default {
  name: "Period",
  data() {
    return {
      // 遮罩层
      loading: false,
      //仓库选择
      optionswarehouse: [],
      selectwarehouse: "",
      warehouseName: "",
      //选择期间
      periodDate: "",
      // 结存查询参数
      queryParams: {
        warehouse: "", //仓库编码
        pageNum: 1,
        pageSize: 100,
      },
      // 结存月份查询
      queryMonth: {
        year: "",
        whCode: "",
      },
      //结存年/月份
      MonthData: [
        "一月",
        "二月",
        "三月",
        "四月",
        "五月",
        "六月",
        "七月",
        "八月",
        "九月",
        "十月",
        "十一月",
        "十二月",
      ],
      balanceMonthStatus: {
        month1: true,
      },
      //结存数据
      BalanceData: [],
      //仓库全部结存-无重复
      balancePeriod: [],
      // 总条数
      total: 0,
      // 最大高度
      maxHeight: null,
      //提交结存
      balanceFrom: {
        period: null,
        whCode: "", //仓库编码
        checkFlag: "",
      },
      //区间查询按钮状态
      periodStatus: true,
      //打印数据
      printData: [],
      title: "",
    };
  },
  created() {
    // 初始化仓库
    this.getHouselList();
    this.periodDate = new Date();
    this.queryMonth.year = this.timeYear(new Date());
  },

  methods: {
    // 仓库列表
    getHouselList() {
      listWarehouses().then((res) => {
        if (res.code == 200) {
          this.optionswarehouse = res.rows;
          if (this.optionswarehouse.length > 0) {
            this.warehouseChange(this.optionswarehouse[0].code);
            this.selectwarehouse = this.optionswarehouse[0].code;
          } else {
            this.loading = false;
          }
        }
      });
    },

    // 仓库选择
    warehouseChange(code) {
      this.queryParams.warehouse = code;
      this.balanceFrom.whCode = code;
      this.queryMonth.whCode = code;
      let wmObj = {};
      wmObj = this.optionswarehouse.find((item) => {
        return item.code == code;
      });
      if (wmObj.period == -1) {
        this.periodStatus = true;
      } else {
        this.periodStatus = false;
      }
      this.warehouseName = wmObj.name;
      this.dateChange();
      this.getBlanceMonth();
      this.getBalanceList();
    },

    //选择结存期间
    dateChange() {
      let date = JSON.parse(JSON.stringify(this.periodDate));
      if (
        this.periodDate !== "" &&
        this.periodDate !== null &&
        this.queryParams.warehouse !== ""
      ) {
        this.timeYearMoubth(date).then((period) => {
          this.balanceFrom.period = period;
        });
      }
    },

    // 获取结存数据
    getBalanceList() {
      this.loading = true;
      listBalance(this.queryParams).then((res) => {
        if (res.code == 200) {
          this.loading = false;
          this.BalanceData = res.rows;
          this.total = res.total;
          this.maxHeight = `${document.documentElement.clientHeight}` - 220;
        }
      });
    },

    //获取结存月份
    getBlanceMonth() {
      this.mounthReset();
      blanceAll({ whCode: this.balanceFrom.whCode }).then((res) => {
        let list = JSON.parse(JSON.stringify(res.data)),
          periodYm = [],
          arrYm = [],
          periodMounth = [],
          mounth = "";
        list.forEach((item) => {
          if (item.checkFlag == "1") {
            item.period = item.period.toString();
            periodYm.push(item.period);
          }
        });
        this.balancePeriod = periodYm;
        this.balancePeriod.forEach((period) => {
          if (period.slice(0, 4) == this.queryMonth.year) {
            arrYm.push(period);
          }
        });
        arrYm.forEach((period) => {
          mounth = period.toString().slice(4, 6);
          periodMounth.push(mounth);
        });

        periodMounth.forEach((item) => {
          if (item == "01") {
            this.balanceMonthStatus.month1 = true;
          }
          if (item == "02") {
            this.balanceMonthStatus.month2 = true;
          }
          if (item == "03") {
            this.balanceMonthStatus.month3 = true;
          }
          if (item == "04") {
            this.balanceMonthStatus.month4 = true;
          }
          if (item == "05") {
            this.balanceMonthStatus.month5 = true;
          }
          if (item == "06") {
            this.balanceMonthStatus.month6 = true;
          }
          if (item == "07") {
            this.balanceMonthStatus.month7 = true;
          }
          if (item == "08") {
            this.balanceMonthStatus.month8 = true;
          }
          if (item == "09") {
            this.balanceMonthStatus.month9 = true;
          }
          if (item == "10") {
            this.balanceMonthStatus.month10 = true;
          }
          if (item == "11") {
            this.balanceMonthStatus.month11 = true;
          }
          if (item == "12") {
            this.balanceMonthStatus.month12 = true;
          }
        });
      });
    },

    // 改变结存年份
    changeYear(type) {
      if (type == "next") {
        this.queryMonth.year = this.queryMonth.year + 1;
        this.getBlanceMonth();
      } else {
        this.queryMonth.year = this.queryMonth.year - 1;
        this.getBlanceMonth();
      }
    },

    // 结存
    handleBalance() {
      this.getAvailable().then((data) => {
        this.balanceFrom.period = data[0].period;
        let period = this.balanceFrom.period.toString();
        this.balanceFrom.checkFlag = "1";
        let y = period.slice(0, 4),
          m = period.slice(4, 6);
        let date = y + "年" + m + "月",
          name = this.warehouseName;
        this.$confirm(
          "确认结存" + "-" + name + " "+date+ "仓库期间",
          "警告",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          }
        )
          .then(() => {
            return balanceWm(this.balanceFrom);
          })
          .then((res) => {
            if (res.code == 200) {
              this.msgSuccess("结存成功");
              this.getBlanceMonth();
              this.getBalanceList();
            }
          });
      });
    },

    //可用期间
    getAvailable() {
      return new Promise((resolve) => {
        blanceAvailable({ whCode: this.balanceFrom.whCode }).then((res) => {
          if (res.code == 200) {
            resolve(res.data);
          }
        });
      });
    },

    //仓库可用期间->用于反结存
    getAllPeriod() {
      return new Promise((resolve, reject) => {
        blanceAll({ whCode: this.balanceFrom.whCode }).then((res) => {
          if (res.code == 200) {
            if (res.data.length > 0) {
              let objPeriod = res.data.find((item) => {
                return item.checkFlag == "1";
              });
              if (objPeriod !== undefined) {
                this.aniStatus = false;
                resolve(objPeriod);
              } else {
                this.msgError("当前没有可反结存期间");
              }
            }else{
              this.msgError("当前没有可反结存期间");
            }
          }
        });
      });
    },

    // 反结存
    handleCounterBalance() {
      this.getAllPeriod().then((data) => {
        this.balanceFrom.period = data.period;
        let period = this.balanceFrom.period.toString();
        this.balanceFrom.checkFlag = "0";
        let y = period.slice(0, 4),
          m = period.slice(4, 6);
        let date = y + "年" + m + "月",
          name = this.warehouseName;
        this.$confirm(
           "确认反结存" + "-" + name + " "+date+ "仓库期间",
          "警告",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          }
        )
          .then(() => {
            return aniBalanceWm(this.balanceFrom);
          })
          .then((res) => {
            if (res.code == 200) {
              this.msgSuccess("反结存成功");
              this.getBlanceMonth();
              this.getBalanceList();
            }
          });
      });
    },

    //导出
    handleExport() {
      const queryParams = this.queryParams;
      let period = this.balanceFrom.period.toString();
      let y = period.slice(0, 4),
        m = period.slice(4, 6);
      let date = y + "年",
        name = this.warehouseName;
      this.$confirm("是否确认导出" + " " + name + " " + "结存单据?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return exportBalance(queryParams);
        })
        .then((response) => {
          this.download(response.msg);
        });
    },

    /** 打印*/
    handlePrint() {
      this.printData = this.BalanceData;
      let period = this.balanceFrom.period.toString();
      let y = period.slice(0, 4),
        m = period.slice(4, 6);
      let date = y + "年",
        name = this.warehouseName;
      this.title = name;
      console.log(this.title);
      setTimeout(() => {
        this.$print(this.$refs.startPrint.$refs.print);
      }, 0);
    },

    //查询所有
    checkAll() {
      this.getBalanceList();
    },

    //时间转换年
    timeYear(date) {
      let time = new Date(date);
      return time.getFullYear();
    },

    //时间转换年月
    timeYearMoubth(date) {
      return new Promise((resolve) => {
        let time = new Date(date),
          newYear,
          newMonth,
          newTime;
        newYear = time.getFullYear().toString();
        if (time.getMonth() + 1 >= 10) {
          newMonth = (time.getMonth() + 1).toString();
        } else {
          newMonth = "0" + (time.getMonth() + 1).toString();
        }
        newTime = newYear + newMonth;
        newTime = parseInt(newTime);
        resolve(newTime);
      });
    },

    // 时间转换当前月+"0"
    timeZero(date) {
      let time = new Date(date);
      if (time.getMonth() + 1 < 10) {
        return time.getFullYear() + "年" + "0" + (time.getMonth() + 1) + "月";
      } else {
        return time.getFullYear() + "年" + (time.getMonth() + 1) + "月";
      }
    },
    //搜索表单重置
    mounthReset() {
      this.balanceMonthStatus = {
        month1: false,
        month2: false,
        month3: false,
        month4: false,
        month5: false,
        month6: false,
        month7: false,
        month8: false,
        month9: false,
        month10: false,
        month11: false,
        month12: false,
      };
    },
  },
  components: {
    PrintPage,
  },
  filters: {
    fliterFlag(status) {
      switch (status) {
        case "0":
          return "反结存";
          break;
        case "1":
          return "结存";
      }
    },
  },
};
</script>
<style lang="scss">
.el-table {
  overflow: inherit;
}

.period-box {
  .top-left {
    display: flex;
    align-items: center;
    justify-content: space-between;
    width: 100%;
  }
  .el-tag--medium {
    width: 58px;
  }
  .el-date-editor {
    width: 150px;

    input {
      height: 28px;
      line-height: 28px;
    }

    .el-input__icon {
      line-height: 28px !important;
    }
  }

  .date-selection {
    color: #606266;
    border: 1px solid #dfe4ed;
    height: 240px;
    box-shadow: 0 2px 12px 0 rgb(0 0 0 / 10%);
    background: #ffffff;
    border-radius: 4px;
    line-height: 30px;

    .date-top {
      margin: 12px;
      text-align: center;
      padding-bottom: 12px;
      border-bottom: solid 1px #e6ebf5;
      margin-bottom: 0;
      label {
        font-size: 14px;
        font-weight: normal;
      }
      .el-picker-panel__icon-btn {
        font-size: 12px;
        color: #303133;
        border: 0;
        background: transparent;
        cursor: pointer;
        outline: none;
        margin-top: 8px;
      }

      .el-date-picker__prev-btn {
        float: left;
      }
    }

    .date-content {
      position: relative;
      margin: 0 15px;

      .content-mounth {
        display: flex;
        flex-wrap: wrap;

        div {
          flex: 0 1 33.333%;
          text-align: center;
          font-size: 12px;
          height: 40px;
          line-height: 40px;
          padding: 8px 0px;

          .today {
            color: #1890ff;
            font-weight: 700;
          }
        }
      }
    }

    .el-month-table {
      width: 100%;
    }
  }

  .per-amount {
    text-align: right;
  }

  .search-box {
    .search-header {
      display: flex;
      align-items: center;
      justify-content: center;

      span {
        width: 65px;
        display: inline-block;
        flex-shrink: 0;
      }

      .el-input--mini .el-input__inner {
        padding-right: 10px;
        padding-left: 10px;
      }

      i {
        font-size: 14px;
        cursor: pointer;
      }

      .el-icon-close {
        font-size: 15px;
        color: #999;
      }
    }

    .box-input {
      position: absolute;
      top: 30px;
      z-index: 999;
      left: 0px;
      right: 0px;
      background: #fff;
      height: 60px;
      box-shadow: 1px 1px 5px #eee;

      .input-t {
        padding: 15px;
      }
    }
  }

  .caret-wrapper {
    position: absolute;
    right: 64px;
    top: -5px;
    display: none;
  }

  .el-table__header,
  .el-table .cell,
  .has-gutter th,
  .el-table thead {
    overflow: inherit !important;
  }

  .el-table th > .cell {
    overflow: inherit;
    position: relative;
  }

  .el-table .el-table__header-wrapper th,
  .el-table .el-table__fixed-header-wrapper th {
    height: 35px;
  }

  .el-table__header,
  .el-table .cell,
  .basicfile-box .has-gutter th,
  .el-table thead {
    overflow: inherit !important;
  }

  // 下拉收起动画
  .toggle-fade {
    transition: all 0.1s linear;
    overflow: hidden;
  }

  .toggle-fade-enter-active {
    animation: downOpen 0.2s linear;
    overflow: hidden;
  }

  .toggle-fade-leave-active {
    animation: downOpen 0.2s reverse linear;
    overflow: hidden;
  }

  @keyframes downOpen {
    from {
      height: 0px;
    }

    to {
      height: 60px;
    }
  }

  .el-table--medium th,
  .el-table--medium td {
    overflow: inherit;
  }

  .el-table th > .cell {
    overflow: inherit;
    position: relative;
  }

  .has-gutter th {
    text-align: center;
    overflow: inherit;
  }

  .el-table__header-wrapper,
  .el-table__footer-wrapper {
    overflow: inherit;
  }

  .purchas-war {
    .con-top {
      display: flex;
      justify-content: space-between;
      align-items: center;

      .top-right {
        display: flex;
        align-items: center;
      }
    }

    .ware-sel {
      width: 150px;

      .el-input__inner {
        height: 28px;
        line-height: 28px;
      }

      .el-input--medium .el-input__icon {
        line-height: 28px;
      }
    }

    .el-input--medium .el-input__icon {
      line-height: 34px;
    }

    .el-table__header-wrapper th,
    .el-table .el-table__fixed-header-wrapper th {
      height: 35px;
    }

    .el-table .warning-row {
      .red-scarlet {
        color: #fc6a6a;
      }
    }

    .has-gutter {
      .el-checkbox__inner {
        margin-right: 4px;
      }
    }

    .el-table tbody tr:hover > td {
      background: none !important;
    }

    .ware-operation {
      .ware-search {
        display: flex;
        margin-bottom: 20px;

        .search-input {
          display: flex;
          margin-right: 15px;

          .input-data {
            min-width: 220px !important;
          }

          .el-input {
            margin-right: 15px;
          }
        }
      }
    }

    .el-table th {
      height: 35px;
    }

    .el-table--medium th,
    .el-table--medium td {
      padding: 4px 0;
      padding-bottom: 3px;
    }

    .el-link--inner {
      margin-left: 3px;
      margin-right: 3px;
      font-size: 12px;
    }
  }

  .tip-box1 {
    text-align: center;
    width: 100%;

    span {
      color: #515a6e;
      font-size: 14px;
    }
  }
}
</style>
